% Backward elimination
% Writen by Lei NIE (nieleimail@gmail.com)
% 13 June 2014

function fcMap = backward_elimination(fData)

% Input:
% fdata: a matrix of fMRI data; each column is the time series of a ROI.

% Output:
% fcMap: a matrix represents functional connectivities.

dSize = size(fData); 
fcMap = zeros(dSize(2));
pCorrelation = partialcorr(fData);

for i = 1:dSize(2)       % use "parfor" for parallelization
    tCor = zeros(1,dSize(2));
    for j = 1:(i-1)
        remain = 1:dSize(2);
        remain([i,j])=[];
        list = zeros(1,(dSize(2)-1));
        for s = 1:(dSize(2)-2)
            lowest = Inf;
            position = 0;
            for k = 1:length(remain)
                filter = remain;
                filter(k)=[];
                pcor = abs(partialcorr(fData(:,i),fData(:,j),fData(:,filter))); %%%%Nan
                if pcor<lowest
                    lowest = pcor;
                    position = k;
                end
            end
            remain(position)=[];
            list(s) = lowest;
        end
        list(dSize(2)-1) = abs(pCorrelation(i,j));
        tCor(j)=min(list);
    end
    fcMap(i,:) = tCor;
end

fcMap = fcMap + fcMap';
